<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>仪器地址变更</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">

		<link rel="stylesheet" href="../../../css/mui.min.css">
		<link rel="stylesheet" href="../../../css/global.css">
		<link rel="stylesheet" href="../../../css/style.css">
		<link rel="stylesheet" href="../../../css/checkbox.css"/>
		<link href="../../../css/task.css" rel="stylesheet" />
		<link rel="stylesheet" href="../../../css/mui.picker.css">
		<link rel="stylesheet" href="../../../css/mui.poppicker.css">
		<style>
			.mui-checkbox label, .mui-radio label{
				padding-left: 20px;
				padding-right: 0;
			}
			.mui-input-row label{
				line-height: 0;
			}
			.mui-input-row label span{
				color: #999999;
			}
			.mui-input-row label span.r{
				margin-right: 30px;
			}
			.mui-checkbox input[type=checkbox], .mui-radio input[type=radio]{
				left: 0;
			}

			.amap-logo {
			    display: none!important;
			}
			.amap-copyright {
			    opacity:0;
			}  
		</style>
		<style type="text/css">
			#div {
				width: 0px;
				height: 0px;
				background: red;
				position: fixed;
				top: 65%;
				left: 50%;
			}
			/*移除底部或顶部三角,需要在删除此代码*/
			.mui-popover .mui-popover-arrow:after {
				width: 0px;
			}
			.updateAddress{
				position: inherit;
			}
			.addrbox{
				padding: 0 10px;
			}
			.addrbox .clum{
				display: flex;
				padding: 0;
			}
			.addrbox .clum .name{
				width: 90px;
			}
			.addrbox .clum input{
				border: none;
				background: none;
				margin-bottom: 0;
				text-align: right;
				height: 48px;
			}
		</style>
	</head>

	<body>
		
		<div id="div"></div>
		<div id="popover" class="mui-popover shadow popover">
			<p class="title">上门地址变更会触发case到800变更仪器安装地址,是否变更?</p>
			<div class="btn_box">
				
				<span class="fl" onclick="closepop()">取消</span>
				<span class="fr red" id="quedingupdate">确定</span>
			</div> 
		</div>
		
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 id="title" class="mui-title">仪器地址变更</h1>
		</header>
		<!-- html代码 start -->
		<div style="width: 100%;height: 300px;" id="container">
			
		</div>
		<div class="updateAddress">
			<div class="cen">
				<p class="tip">提示：签到地址与客户地址不一致，是否申请更改？</p>
				<div class="line"></div>
				<div class="clum autoHeight">
					<div class="mui-input-row mui-checkbox zp_check">
						<label id="oldAddress" style="line-height: inherit;">原地址</label>
					</div>
				</div>
				<div class="clum autoHeight">
					<div class="mui-input-row mui-checkbox zp_check">
						<input name="checkbox" value="1" type="checkbox">
						<label>当前地址</label>
					</div>
					<div class="clear"></div>
					<div class="details_con addrbox">
						<div class="clum" style="margin: 0">
							<span class="name">省<em class="t_red">*</em></span>
							<input id="province" class="showCityPicker3"  type="text" readonly>
						</div>
						<div class="clum" style="margin: 0">
							<span class="name">市<em class="t_red">*</em></span>
							<input id="city" class="showCityPicker3"  type="text" readonly>
						</div>
						<div class="clum" style="margin: 0">
							<span class="name">区<em class="t_red">*</em></span>
							<input id="district" class="showCityPicker3"  type="text" readonly>
						</div>
					<div  style="margin:10px 0 0; display: block; height: auto">
						<span class="name">详细地址<em class="t_red">*</em></span>
						<div class="clear"></div>
						<div class="textArea" style="margin: 10px 0 0 0">
							<textarea id="detailAddr"></textarea>
<!--							<textarea id="instAddress"></textarea>-->
						</div>
					</div>
					</div>
<!--					<button style="color: #a4a4a4;" id='showCityPicker3' class="mui-btn-select" type='button'>请选择所在地区</button>-->


				</div>
				<div class="line"></div>
				<div class="autoHeight lat">
					<div class="mui-input-row mui-checkbox zp_check" style="font-size: 16px;">
						<input name="checkbox" value="2" type="checkbox">
						<label>经度：<span class="r" id="longitude"></span>纬度：<span id="latitude"></span></label>
					</div>
				</div>
				<div class="btn_box">
					
					<span class="fl" id="cancel">取消</span>
					<span class="fr red"  id="save">确定</span>
				</div>
				<div style="height: 50px;"></div>
			</div>
			
		</div>
			<!-- <div class="details_con">
				<div class="clum">
					提示：签到地址与客户地址不一致，是否申请更改?
				</div>
				<form class="mui-input-group">
					<div class="mui-input-row mui-checkbox mui-left">
						
						<label>上门地址<input type="text" class="d_ipt" value="上海市杨浦区淞沪路2005号" /></label>
						<input name="checkbox" value="1" type="checkbox" >
	
					</div>
					<div class="mui-input-row mui-checkbox mui-left">
						
						<input name="checkbox" value="2" type="checkbox">
					</div>
				</form>
				<div class="clum">
					<span class="name">经度</span>
					<input type="text" class="d_ipt" placeholder="" id="longitude"/>
				</div>
				<div class="clum">
					<span class="name">纬度</span>
					<input type="text" class="d_ipt" placeholder="" id="latitude"/>
				</div>
				<div id="container" style="width: 100%;height: 300px;">
					
				</div>
			</div>
			<div class="btn_box">
				<span class="fl red" id="save">保存</span>
				<span class="fr">取消</span>
			</div>
			<div style="height: 50px;"></div>
		</div> -->

		<!-- js代码 start -->

		<!-- 基础js start -->
		<script src="../../../js/mui.min.js"></script>
		<script src="../../../js/utils/h.js"></script>
		<script src="../../../js/constant.js"></script>
		<script src="../../../js/common.js"></script>
		<script src="../../../js/utils/base64.js"></script>
		<script src="../../../js/utils/md5.js"></script>
		<script src="../../../js/utils/sortMap.js"></script>
		<script src="../../../js/utils/http.js"></script>
		<script src="../../../js/app.js"></script>
		<script src="../../../js/sqliteTools.js"></script>
		<!-- 基础js end -->
		<script src="../../../js/mui.picker.js"></script>
		<script src="../../../js/mui.poppicker.js"></script>
		<script src="../../../js/city.data-3.js"></script>
		<script src="../../../js/utils/rolldate.min.js"></script>
		<script src="https://webapi.amap.com/maps?v=1.4.15&key=1ca9acc9d0ea8d20406b89acb63c2b4a&plugin=AMap.Geocoder"></script>
		<script type="text/javascript" charset="utf-8">
			var serviceNo;
			var ServiceNoticeIds;
			var serviceNos;
			var planIds;
			var longitude;
			var latitude;
			var newLongitude;
			var newLatitude;
			var newAddress;
			var address;
			var noticeId;
			var dizhi = false;
			var jwd = false;
			var self;
			var listName;
			var customerName;
			// 取消方法 关闭弹窗
			function closepop(){
				mui("#popover").popover('hide', document.getElementById("div"));
			}
			
			 //mui初始化
			(function($, doc) {
				$.init();

				var addrPicker = new $.PopPicker({layer:3});
				addrPicker.setData(cityData3);
				$('.details_con').on('click','.showCityPicker3',function () {
					addrPicker.show(function(items) {
						console.log(items)
						h("#province").val(items[0].text)
						h("#city").val(items[1].text)
						h("#district").val(items[2].text)
					});
				})

				$.plusReady(function() {					
					// 获取定位的经纬度
					app.showWaiting('加载中...')
					plus.geolocation.getCurrentPosition(function(p){
						longitude = p.coords.longitude;
						latitude = p.coords.latitude;
						
						newLongitude = longitude;
						newLatitude = latitude;
						
						var lnglat = longitude+","+latitude;
						var geocoder = new AMap.Geocoder({
							city: "010", //城市设为北京，默认：“全国”
							radius: 1000 //范围，默认：500
						});
						geocoder.getAddress(lnglat, function(status, result) {
							if (status === 'complete'&&result.regeocode) {
								newAddress = result.regeocode.formattedAddress;
								var addrEle=result.regeocode.addressComponent;
								console.log(result)
								console.log(addrEle)
								h("#instAddress").val(result.regeocode)

								h("#province").val(addrEle.province)
								var city = addrEle.city;
								if(addrEle.province == "北京市" || addrEle.province == "天津市" || addrEle.province == "上海市" || addrEle.province == "重庆市"){
									city = addrEle.province;	
								}
								h("#city").val(city)
								h("#district").val(addrEle.district)
								h("#detailAddr").val(addrEle.township + addrEle.street +addrEle.streetNumber)

								cityData3.forEach(function (item) {
									if(item.text === addrEle.province){
										addrPicker.pickers[0].setSelectedValue(item.value)
										item.children&&item.children.forEach(function (city) {
											if (city.text === addrEle.city){
												addrPicker.pickers[1].setSelectedValue(city.value)
												city.children && city.children.forEach(function(district){
													if(district.text === addrEle.district){
														addrPicker.pickers[2].setSelectedValue(district.value)
													}

												})
											}
										})
									}
								})

							}else{
								console.log('根据经纬度查询地址失败')
							}
						});
						// 进入页面查询仪器原位置信息
						getInstrument()				
					}, function(e){
						app.closeWaiting();
						app.toast("定位失败");
					}, {geocode: false});
					
					// 取消方法
					h("#cancel").tap(function(){
						qiandao6()
					});
									
					// 从上一个页面取值
					self = plus.webview.currentWebview();
					// 获取上一个页面传过来的参数并显示到页面
					ServiceNoticeIds = self.ServiceNoticeIds;
					serviceNos = self.serviceNos;
					serviceNo = self.serviceNo;
					noticeId = self.noticeId;
					planIds = self.planIds;
					listName = self.listName;
					customerName = self.customerName;
					
					// 保存
					h("#save").tap(function() {
						dizhi = false;
						jwd = false;
						// 获取checkbox的值
						var ele = document.getElementsByName("checkbox");
						for (var i = 0; i < ele.length; i++) {
							// console.log(ele[i].value + ": " + ele[i].checked)
							if(ele[i].checked){
								if(ele[i].value=="1"){
									dizhi = true;
								} 
								if(ele[i].value=="2"){
									jwd = true;
								}
							}
						}
						if(!dizhi && !jwd){
							app.toast("请勾选")
							return
						}
						// 如果选中修改上门地址提示弹窗
						if(dizhi)
						{
							if(!h('#detailAddr').val()){
								app.toast("请填写详细地址")
								return false
							}
							// 弹窗提示
							mui("#popover").popover('toggle', document.getElementById("div"));
							return
						}
						// 否则不弹出
						else{

							// // 验证是否勾选修改经纬度，如果勾选更新经纬度
							// if(jwd){
							// 	// 调用更新经纬度的方法
							// 	updateLonLat();
							// }
							// // 跳转页面
							// tiaozhuan()
							baocun()
						}

					});
							
				});
				
				// 确定更新上门地址方法
				h("#quedingupdate").tap(function(){
					baocun()
				});

			}(mui, document));
			
			// 查询当前仪器的地址和经纬度
			function getInstrument(){
				ajaxGet(BASE_URL + "cc/instrument/getInstrument", {
					"ServiceNoticeId": noticeId
				}, function(data) {
					app.closeWaiting()
					if (data.code == 200) {
						// longitude = data.data[0].longitude;
						// latitude = data.data[0].latitude;
						address = data.data[0].instAddress;
						id = data.data[0].id;
						
						h("#oldAddress").html("原地址："+address);
						h("#longitude").html(longitude.toFixed(7));
						h("#latitude").html(latitude.toFixed(7));
						
						// 调用地图初始化方法
						mapinit();
					} else {
						app.toast(data.msg);
					}
				}, function(errorMsg) {
					app.closeWaiting();
					app.toast(errorMsg);
				});
			}
			
			// 地图初始化方法
			function mapinit(){
				var map = new AMap.Map('container', {
				    resizeEnable: true, //是否监控地图容器尺寸变化
				    zoom:13, //初始化地图层级
				    center: [longitude, latitude] //初始化地图中心点
				});
				// 构造点标记
				var marker = new AMap.Marker({
				    icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
				    position: [longitude, latitude],
					draggable: true
				});
				map.add(marker);
				// 坐标点添加拖拽事件
				marker.on('dragging', function(e){
					longitude = e.lnglat.getLng();
					latitude = e.lnglat.getLat();
					console.log("Geolocation longitude:"+longitude+"	latitude:"+latitude);
					h("#longitude").html(longitude.toFixed(7));
					h("#latitude").html(latitude.toFixed(7));
				});				
				// map.setFitView();
			}
			
			// 更新经纬度信息
			// function updateLonLat(){
			// 	ajaxGet(BASE_URL + "cc/instrument/updateInstrument", {
			// 		"ServiceNoticeIds": ServiceNoticeId,
			// 		"longitude": longitude,
			// 		"latitude": latitude
			// 	}, function(data) {
			// 		console.log(JSON.stringify(data))
			// 		if(data.code==200){
			// 			app.toast("操作成功");
			// 		}
			// 	}, function(errorMsg) {
			// 		console.log(JSON.stringify(errorMsg))
			// 	});
			// }
			
			function baocun(){
				app.showWaiting('正在提交...')
				// var instAddress = h("#instAddress").val();
				var instAddress = h("#province").val()+h("#city").val()+h("#district").val()+h('#detailAddr').val();
				ajaxPost(BASE_URL + "cc/instrument/updateApply", {
					"enginnerId": app.getUser().enginnerId,
					"serviceNo": serviceNos,
					"remarks": "原地址："+address+",新上门地址："+instAddress,
					"parameter": instAddress,
					"type": "2",
					"serviceNoticeId": ServiceNoticeIds,
					"longitude": longitude,
					"latitude": latitude,
					"dizhi":dizhi,
					"jwd":jwd
				}, function(data) {
					app.closeWaiting()
			
					if(data.code==200){
						qiandao6();
					}else{
						app.toast(data.msg);
					}
				}, function(errorMsg) {
					app.closeWaiting()
					console.log(JSON.stringify(errorMsg))
				});
			}
		
			function qiandao6(){
				if (listName && listName == "infoUpdate"){	
					mui("#popover").popover('hide', document.getElementById("div"));
					mui.back();
				} else {
					ajaxGet(BASE_URL + "cc/PlanDetails/fseSign", {
						"relServiceNo": serviceNo,
						"ServiceNoticeIds": ServiceNoticeIds,
						"serviceNos": serviceNos,
						"planIds": planIds,
						"EnginnerId": app.getUser().enginnerId,
						"longitude": newLongitude,
						"latitude": newLatitude
					}, function(data) {
						app.closeWaiting()
						if(data.code==200){ 
							if(data.data && data.data.length > 0){
								// 判断是否存在离线数据，
								var enginnerId = app.getUser().enginnerId;
								var fseName = app.getUser().name;
								var sqliteTool = new sqliteTools(); 
								sqliteTool.openDatabase();
								for (var i = 0; i < data.data.length; i++) {
									var resData = data.data[i];	
									sqliteTool.selectServiceByPlanId(enginnerId, resData.planId, resData, function(flag, offlineData, callBackData) {	
										if(flag){	
											if (offlineData && offlineData.length > 0) {
												sqliteTool.insertServiceSignInData(offlineData[0].id, "1", callBackData.signInTime, newLongitude, newLatitude, "0", function(flag) {
													console.log("更新本地签到数据"+flag)											
												});											
											} else {
												sqliteTool.insertServiceBaseAndSignInData(callBackData.serviceNo, callBackData.serviceNoticeId, callBackData.planId, customerName, callBackData.instrumentId, callBackData.instSn, callBackData.acceptTime, enginnerId, fseName, callBackData.serviceType, callBackData.subServiceType, "1", callBackData.signInTime, newLongitude, newLatitude, function (flag) {
													console.log("插入本地签到数据"+flag)											
												})
											}
										}
									});								
								}	
								setTimeout(function() {
									sqliteTool.closeDB();
									app.toast("签到成功")
									tiaozhuan()
								}, 500);									
							} else {
								app.toast("签到成功")
								tiaozhuan()
							}						
						}else{
							app.toast(data.msg)
						}
					}, function(errorMsg) {
						app.closeWaiting()
						app.toast(errorMsg)
					});
				}
			}
			
			// 跳转页面方法
			function tiaozhuan(){
				// 跳转到签到列表页面
				// 查找上级页面并关闭页面
				var relationNotices = plus.webview.getWebviewById('view/service/notice/relationNotices.html');
				if (relationNotices) {
					relationNotices.close()
				}
				
				var signIn = plus.webview.getWebviewById('view/service/notice/signIn.html');
				if (signIn) {
					signIn.close()
				}
				
				var signInAddReport = plus.webview.getWebviewById('view/service/notice/signInAddReport.html');
				if (signInAddReport) {
					signInAddReport.close()
				}
				
				// 关闭进行中
				var conductList = plus.webview.getWebviewById('view/service/assign/conductList.html');
				if(conductList){
					conductList.close()
				}
				
				// 关闭工作台查询未关闭服务通知列表
				var notClosedList = plus.webview.getWebviewById('view/service/notice/notClosedList.html');
				if(notClosedList){
					notClosedList.close()
				}
				
				// 1、刷新FSE首页
				var indexFSE = plus.webview.getWebviewById('view/main/indexFSE.html');
				if(indexFSE){
					indexFSE.evalJS('getList("1")')
				}
				
				// 关闭工作台已接受列表
				var acceptedList = plus.webview.getWebviewById('view/service/notice/acceptedList.html');
				if(acceptedList){
					acceptedList.close()
				}

				 // 查找需要跳转的页面，并指定刷新的方法
				var checkedInList = plus.webview.getWebviewById('view/service/notice/checkedInList.html');
				if(checkedInList){
					checkedInList.evalJS('initData()')
					mui.back()
				}else{
					var checkedInList1 = plus.webview.create('/view/service/notice/checkedInList.html','view/service/notice/checkedInList.html')
					checkedInList1.show()
					var self = plus.webview.currentWebview();
					self.close();
				}
				
			}
		</script>
		<!-- js代码 end -->

	</body>

</html>
